import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Upload, message } from 'antd';
import { useState } from 'react';

import styles from './index.less';
type Props = {
  isModalVisible: boolean;
  setIsModalVisible: (b: boolean) => void;
};

export default function UploadAvatar(props: Props) {
  const { isModalVisible, setIsModalVisible } = props;
  const [loading] = useState(false);
  const [imageUrl] = useState('');
  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <Modal title="上传头像" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
      <div className={styles.upload}>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          beforeUpload={beforeUpload}
          onChange={() => {}}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      </div>
      <div className={styles.word} style={{ textAlign: 'center' }}>
        只支持jpg、png格式的图片，大小不超过2M
      </div>
    </Modal>
  );
}
